import { Asset, Component, resources, Size, SpriteAtlas, Vec2, Vec3 } from "cc";

export class GameTools extends Component {

    /**得到一个在 [min, max - 1] 区间内的随机整数 */
    public static RandomByRange(min: number, max: number) {
        return Math.floor(Math.random() * (max - min) + min)
    }
    /**将数组内容进行随机排列*/
    public static getRandomArr(array: any[]): any[] {
        // 打乱数组顺序(关键)
        array.sort(function () { return 0.5 - Math.random(); });
        // 得到随机数组，按顺序取出，完美解决随机不重复
        return array;
    }

    public static loadResAsync(path: string, type: typeof Asset): Promise<any> {
        if (path == '') {
            return null
        }
        return new Promise((resolve, reject) => {
            resources.load(path, type, (error: Error, resource: any) => {
                if (error) {
                    reject(error)
                } else {
                    console.log(`加载资源-->from res async--> ${path}`)
                    resolve(resource)
                }
            })
        })
    }

    /** 矩形和矩形碰撞 */
    public static checkRectRect(rp0: Vec3, size0: Size, rp1: Vec3, size1: Size) {
        const difX = Math.abs(rp0.x - rp1.x);
        const difY = Math.abs(rp0.y - rp1.y);
        const width = (size0.width + size1.width) / 2;
        const height = (size0.height + size1.height) / 2;
        return difX <= width && difY <= height;
    }
    /** 生成一个永不重复的ID 引入时间戳 + 36进制版本 + 随机数长度控制*/
    public static GenNonDuplicateID(randomLength: number) {
        let idStr = Date.now().toString(36)
        idStr += Math.random().toString(36).substr(2, randomLength)
        return idStr
    }
}